﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using VictorBlaga.DocumentManagement.Core.Models.Repositories;
using VictorBlaga.DocumentManagement.Infrastructure;
using VictorBlaga.DocumentManagement.Models;

namespace VictorBlaga.DocumentManagement.Helpers.Validators.Impl
{
    public class TeamValidator : ITeamValidator
    {
        private TeamViewModel _viewModel;
        private List<ValidationError> _validationErrors;
        private readonly ITeamRepository _teamRepository;

        public TeamValidator(ITeamRepository teamRepository)
        {
            _teamRepository = teamRepository;
        }

        public TeamViewModel ViewModel
        {
            get { return _viewModel; }
            set
            {
                _viewModel = value;
                _validationErrors = new List<ValidationError>();
            }
        }

        public bool IsInsertValid()
        {
            return IsValid();
        }

        public ValidationError[] GetInsertValidationErrors()
        {
            return GetValidationErrors();
        }

        public bool IsUpdateValid()
        {
            return IsValid();
        }

        public ValidationError[] GetUpdateValidationErrors()
        {
            return GetValidationErrors();
        }

        private bool IsValid()
        {
            if (String.IsNullOrEmpty(_viewModel.Name))
                _validationErrors.Add(new ValidationError("Name must not be empty.", "Name"));
            else if (!_teamRepository.IsUniqueName(_viewModel.Id, _viewModel.Name))
                _validationErrors.Add(new ValidationError("Name already exists. Chose another one.", "Name"));
            if (_viewModel.ManagerId == null)
                _validationErrors.Add(new ValidationError("You have to select a manager.", "ManagerId"));
            
            return _validationErrors.Count == 0;
        }

        private ValidationError[] GetValidationErrors()
        {
            return _validationErrors.ToArray();
        }
    }
}
